package com.sam.im.heiqun.uis.activities;

import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.YaoyiYao;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.ScreenUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import com.sam.im.heiqun.utils.StringUtils;

public class ShakeActivity extends BaseSwipeBackActivity implements SensorEventListener, AMapLocationListener {


    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.shake_top_line)
    ImageView topLineIv;
    @BindView(R.id.shake_top_layout)
    LinearLayout topLayout;
    @BindView(R.id.shake_bottom_line)
    ImageView bottomLineIv;
    @BindView(R.id.shake_bottom_layout)
    LinearLayout bottomLayout;
    @BindView(R.id.linear)
    LinearLayout linearLayout;
    @BindView(R.id.img_bottom)
    ImageView imgbottom;
    private SensorManager sensorManager = null;
    private Vibrator vibrator = null;
    private boolean isShake = false;
    private PGService pgService;
    private PopupWindow mPopWindow = null;
    private MediaPlayer media1;
    private MediaPlayer media2;

    @Override
    public int getContentViewId() {
        return R.layout.activity_shake;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.yao_yao);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        topLineIv.setVisibility(View.GONE);
        bottomLineIv.setVisibility(View.GONE);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
        pgService = PGService.getInstance();
        getlocation();
    }

    @OnClick(R.id.pre_v_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    private void showPopupWindow(final YaoyiYao yaoyiyao) {
        //设置contentView
        View contentView = LayoutInflater.from(ShakeActivity.this).inflate(R.layout.pup_yaoyiyao, null);
        mPopWindow = new PopupWindow(ShakeActivity.this);
        mPopWindow.setContentView(contentView);
        mPopWindow.setWidth(ScreenUtil.getScreenWidth(ShakeActivity.this) * 7 / 8);
        mPopWindow.setHeight(ScreenUtil.dp2px(100));
        YaoyiYao.UserBean user = yaoyiyao.getUser();
        ImageView img = (ImageView) contentView.findViewById(R.id.img_icon);
        TextView tvName = (TextView) contentView.findViewById(R.id.tv_name);
        TextView tvdistense = (TextView) contentView.findViewById(R.id.tv_location);
        ImageView imgsex = (ImageView) contentView.findViewById(R.id.img_sex);
        RelativeLayout relative_pop = (RelativeLayout) contentView.findViewById(R.id.relative_pop);
        relative_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ShakeActivity.this, FriendDetailActivity.class);
                intent.putExtra("id", Long.parseLong(yaoyiyao.getUser().getId()));
                intent.putExtra("type", 0);
                startActivity(intent);
            }
        });
        Glide.with(ShakeActivity.this).load(user.getHeadUrl()).into(img);
        tvName.setText(user.getName());
        String distance = yaoyiyao.getDistance();
        float dis = Float.parseFloat(distance);

        float i1 = dis / 2000;//公里
        int diss = (int) i1;
        String dissss = "";
        if (diss == 0) {
            dissss = getResources().getString(R.string.juli_gongli_1);
        } else {
            dissss = getResources().getString(R.string.juli_you) + diss + getResources().getString(R.string.gongli);
        }
        tvdistense.setText(dissss);
        if (!StringUtils.isEmpty(user.getSex())) {
            imgsex.setVisibility(View.VISIBLE);
            switch (user.getSex()) {
                case "男":
                    imgsex.setImageResource(R.drawable.manimg);
                    break;
                case "女":
                    imgsex.setImageResource(R.drawable.womenimg);
                    break;
            }
        } else {
            imgsex.setVisibility(View.GONE);
        }
        // mPopWindow.setAnimationStyle(R.style.popwin_anim_style);
        //设置各个控件的点击响应
        //显示PopupWindow
        //  backgroundAlpha(0f);
        //mPopWindow.showAsDropDown(imgbottom,0,50);
        ColorDrawable dw = new ColorDrawable(0000);
        mPopWindow.setBackgroundDrawable(dw);
        mPopWindow.showAtLocation(imgbottom, Gravity.BOTTOM, 0, -80);

    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        int sensorType = event.sensor.getType();
        // values[0]:X轴，values[1]：Y轴，values[2]：Z轴
        float[] values = event.values;
        if (sensorType == Sensor.TYPE_ACCELEROMETER) {
            if ((Math.abs(values[0]) > 10 || Math.abs(values[1]) > 10 || Math
                    .abs(values[2]) > 15) && !isShake) {
                isShake = true;
                new Thread() {
                    public void run() {
                        try {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    // 摇动手机后，再伴随震动提示~~
                                    vibrator.vibrate(300);
                                    topLineIv.setVisibility(View.VISIBLE);
                                    bottomLineIv.setVisibility(View.VISIBLE);
                                    startAnimation(false);
                                    media1 = MediaPlayer.create(ShakeActivity.this, R.raw.shake_sound_male);
                                    media1.start();
                                    Log.i("info", "11111");
                                }
                            });
                            Thread.sleep(500);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    vibrator.vibrate(300);
                                    Log.i("info", "22222");
                                }
                            });
                            Thread.sleep(500);
                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    isShake = false;
                                    startAnimation(true);
                                    Log.i("info", "33333");
                                    yaoyiyao();
                                    //  showPopupWindow();
                                }
                            });
                        } catch (InterruptedException e) {

                            e.printStackTrace();
                        }
                    }

                    ;
                }.start();
            }
        }
    }

    private void yaoyiyao() {
        if (mPopWindow != null) {
            mPopWindow.dismiss();
        }
        //showProgress("正在寻找中...");
        String lat = ToolsUtils.getSf(ShakeActivity.this, "lat");
        String lnt = ToolsUtils.getSf(ShakeActivity.this, "lnt");
        pgService.yaoyiyao(lat, lnt, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<YaoyiYao>() {
            @Override
            protected void onResultError(ApiException ex) {
                ToolsUtils.showToast(ShakeActivity.this, getResources().getString(R.string.no_now_yaoyao));
            }

            @Override
            public void onNext(YaoyiYao yaoyiYao) {
                if (yaoyiYao != null) {
                    media2 = MediaPlayer.create(ShakeActivity.this, R.raw.shake_match);
                    media2.start();
                    showPopupWindow(yaoyiYao);
                } else {
                    ToolsUtils.showToast(ShakeActivity.this, getResources().getString(R.string.no_now_yaoyao));
                }
            }
        });
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    private void startAnimation(boolean isBack) {
        int type = TranslateAnimation.RELATIVE_TO_SELF;
        float topFromYValue;
        float topToYValue;
        float bottomFromYValue;
        float bottomToYValue;
        if (isBack) {
            topFromYValue = -0.5f;
            topToYValue = 0;
            bottomFromYValue = 0.5f;
            bottomToYValue = 0;
        } else {
            topFromYValue = 0;
            topToYValue = -0.5f;
            bottomFromYValue = 0;
            bottomToYValue = 0.5f;
        }
        TranslateAnimation topAnimation = new TranslateAnimation(type, 0, type,
                0, type, topFromYValue, type, topToYValue);
        topAnimation.setDuration(200);
        topAnimation.setFillAfter(true);
        TranslateAnimation bottomAnimation = new TranslateAnimation(type, 0,
                type, 0, type, bottomFromYValue, type, bottomToYValue);
        bottomAnimation.setDuration(200);
        bottomAnimation.setFillAfter(true);
        if (isBack) {
            bottomAnimation
                    .setAnimationListener(new TranslateAnimation.AnimationListener() {

                        @Override
                        public void onAnimationStart(Animation animation) {


                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {


                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            topLineIv.setVisibility(View.GONE);
                            bottomLineIv.setVisibility(View.GONE);
                        }
                    });
        }
        bottomLayout.startAnimation(bottomAnimation);
        topLayout.startAnimation(topAnimation);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);//定位时间
                Log.i("info", "定位成功==" + amapLocation.getLatitude() + "  " + amapLocation.getLongitude());
                mlocationClient.stopLocation();
                HashMap<String, String> map = new HashMap<>();
                map.put("lat", amapLocation.getLatitude() + "");
                map.put("lnt", amapLocation.getLongitude() + "");
                ToolsUtils.saveSf(ShakeActivity.this, map);
                hideProgress();
                PGService.getInstance().uplocation(amapLocation.getLatitude() + "", amapLocation.getLongitude() + "", ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                    @Override
                    protected void onResultError(ApiException ex) {

                    }

                    @Override
                    public void onNext(ValidateEntivity validateEntivity) {
                        if (validateEntivity != null) {
                            Log.i("info", "位置提交成功==" + validateEntivity.getInfo());
                        }
                    }
                });
            } else {
                mlocationClient.stopLocation();
                mlocationClient.startLocation();
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

    public AMapLocationClientOption mLocationOption = null;
    public AMapLocationClient mlocationClient = null;

    //定位
    public void getlocation() {

        //声明mLocationOption对象
        mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();
    }

    @Override
    protected void onDestroy() {
        hideProgress();
        if (mPopWindow != null) {
            mPopWindow.dismiss();
        }
        if (media1 != null) {
            if (media1.isPlaying())
                media1.stop();
            media1.release();
        }
        if (media2 != null) {
            if (media2.isPlaying())
                media2.stop();
            media2.release();
        }
        super.onDestroy();
    }
}
